<template>
  <div class="auth-page">
    {{ msg }}
    <nut-toast v-bind="toast" v-model:visible="toast.show" />
  </div>
</template>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import useToast from '@/hooks/useToast'
import getOpenid from '@/api/login'
import { saveAfterSuccessfulLogin, setStorage } from '@/utils/storage'
import { ref } from 'vue'
import useAuthShare from './hooks/useAuthShare'
let { toast, toastFail } = useToast()

const msg = ref('')

const { isShare, toSharePage, shareUrl } = useAuthShare()

// 重新登录或者去注册
wx.login({
  async success(res) {
    if (res.code) {
      login(res.code)
    } else {
      toastFail('登录失败！' + res.errMsg)
      msg.value = res.errMsg
    }
  },
  fail(e) {
    toastFail(e.errMsg)
    msg.value = e.errMsg
  },
})

function toHomePage() {
  Taro.switchTab({
    url: '/pages/index/index',
  })
}

function toLoginPage() {
  Taro.redirectTo({
    url: '/pages/login/index?shareUrl=' + shareUrl,
  })
}

async function login(code) {
  let { miniProgram } = Taro.getAccountInfoSync()
  const { openid, token, customer_id, customer_name } = await getOpenid({
    appId: miniProgram.appId,
    js_code: code,
  })

  setStorage('openid', openid)

  if (token) {
    // 已注册情况

    // 保存登录数据
    saveAfterSuccessfulLogin({ token, customer_id, customer_name })

    if (isShare) {
      toSharePage()
    } else {
      toHomePage()
    }
  } else {
    // 未注册去登录页面注册
    toLoginPage()
  }
}
</script>

<style lang="scss">
.auth-page {
  padding: 60px 0;
  text-align: center;
  color: $color-red;
  font-size: 20px;
}
</style>
